# -*- coding: utf-8 -*-
import requests
import re
from bs4 import BeautifulSoup
import sys
import json
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
import warnings
warnings.filterwarnings("ignore")
import time

"""
功能：获取商品尺码信息，返回给php
"""

def adidas(spurl):
	session=requests.Session()
	loginHead={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
			   'Referer': 'http://store.nike.com/cn/zh_cn/'}
			   
	spHtml=session.get(spurl,headers=loginHead,verify=False)

	#print spHtml.text

	soup=BeautifulSoup(spHtml.text,'html.parser')
	
	itemId=soup.select('#itemId')[0]['value']
	itemId_url='https://www.adidas.com.cn/product/getItemIvts.json?itemId='+itemId+'&_=1503026886081'
	itemId_head={'Host':'www.adidas.com.cn',
				'Referer':'https://www.adidas.com.cn/item/CG4196',
				'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
				'X-CSRF-TOKEN':'20c33053-1937-4654-b63e-78a294b98150',
				'X-Requested-With':'XMLHttpRequest'}
	itemId_Resp=session.get(itemId_url,headers=itemId_head,verify=False)
	info=json.loads(itemId_Resp.text)['skuStr']
	infoDict={}
	for infos in json.loads(info):
		skuId=(infos['skuId'])
		ipi=json.loads(infos['properties'])[1]
		infoDict[ipi]=skuId
	list1 = [(k,infoDict[k]) for k in sorted(infoDict.keys())]

	infoDict2 = {}
	tag = soup.select('.product-size li')
	for tags in tag:
		sizetext = tags.text
		ipi2 = tags['ipi']
		infoDict2[ipi2] = sizetext
	list2 = [(k,infoDict2[k]) for k in sorted(infoDict2.keys())]

	sizetext=[]
	sizeVal=[]
	for text,val in zip(list1,list2): #sizetext==skuId
		if val[1].replace("\n","")[-1]=='½':
			 value = val[1].replace("\n","")[0:-1]+'.5'
		else:
			value = val[1].replace("\n","")
		sizeVal.append(value)
		sizetext.append(text[1])
	return {"allSize":(sizeVal,sizetext)}


def nikeSize(spurl):
	print 'get size...'
	session = requests.Session()
	loginHead={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
			   'Referer': 'http://store.nike.com/cn/zh_cn/',
			   'host':'www.nike.com'} #访问ip
	spHtml=session.get(spurl,headers=loginHead,verify=False)
	time.sleep(1)
	#print spHtml.text
	productid = re.search(r'"product":{"id":"(.*?)"',spHtml.text).group(1)
	build = re.search(r"'build', '(.*?)'",spHtml.text).group(1)
	#print build,productid

	getsize_url = 'https://api.nike.com/deliver/available_skus/v1/'
	sizeHead = {'authority':'api.nike.com',
				'scheme':'https',
				'content-type':'application/json; charset=UTF-8',
				'origin':'https://www.nike.com',
				'referer':'https://www.nike.com/cn/launch/t/kobe-ad-detached',
				'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}

	params={'filter':'productIds('+productid+')'}

	size_infoResp = session.get(getsize_url,headers=sizeHead,params=params,verify=False)
	time.sleep(1)
	#print size_infoResp.text
	text=[]
	for object in json.loads(size_infoResp.text)['objects']:
		if object['available'] == True: #只取有货尺码
			#print object['skuId']
			text.append(object['skuId']) #所有有货尺码商品


	url = 'https://api.nike.com/merch/skus/v2/?filter=productId('+productid+')&filter=country(CN)'
	head = {'content-type':'application/json; charset=UTF-8',
			'Origin':'https://www.nike.com',
			'Referer':'https://www.nike.com/cn/launch/t/air-vapormax-cool-grey-dark-grey',
			'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}
	resp = session.get(url,headers=head,verify=False)

	sizetext=[]
	sizeVal=[]
	for object in json.loads(resp.text)['objects']:
		sizetext.append(object['id'])
		sizeVal.append(object['countrySpecifications'][0]['localizedSize'])

	size = []
	for texts in text:
		size.append(sizeVal[sizetext.index(texts)]) 
	return {"allSize":[size,text]}



	# soup=BeautifulSoup(spHtml.text,'html.parser')
	# #print spHtml.text
	# sizeList=[]
	# sizes=soup.select('option')
	# for size in sizes:
	# 	sizeList.append(size['value'])
	# sizeList = [x for x in sizeList if sizeList.count(x) == 1] #去除无货尺码，无货尺码在该list中有重复值
	
	# sizetext=[]
	# sizeVal=[]
	# for size in sizeList:
	# 	sizeVal.append(size.split(':')[0])
	# 	sizetext.append(size.split(':')[1])

	# return {"allSize":(sizetext,sizeVal)}



if __name__ == '__main__':
	
	website=sys.argv[2]
	# website='3'
	# spurl='https://www.nike.com/cn/launch/t/air-foamposite-pro-island-green'
	if website=='1':
		print json.dumps(adidas(sys.argv[1]))
	if website=='3':
		print json.dumps(nikeSize(sys.argv[1]))